import React, { PureComponent, Fragment } from 'react';
import { Tabs, Row, Typography, Col, Button, Icon, Select, Form, Popover, message } from 'antd';
import qs from 'qs';
import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import moment from 'moment';
import * as utils from '../utils/treeUtils';
import { showConfirm } from '@/utils/utils';
import Alteration from './Aletratinon';
import TextScroll from './TextScroll';
import * as api from '@/services/PriceMgr';
import * as apis from '@/services/ValueApprovelMgr';
import AuthorizedButton from '@/components/AuthorizedButton';
import ApprovalStatus from '@/components/ApprovalStatus';
import MyBasicInfo from '@/components/MyBasicInfo';
import { setValueReportVersionName } from '@/utils/versions_name';

const { Text } = Typography;
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  versions: state.PriceManageVersions.data,
  searchItems: state.PriceManageItems.searchItems,
  versionDetail: state.PriceManageItems.versionDetail,
}))
@Form.create()
export default class PageTop extends PureComponent {
  state = {
    expandForm: false,
    visible: false,
    productType: '',
    product: '',
    build: '',
    decorationStandard: '',
    area: '',
  };

  componentWillReceiveProps(nextProps) {
    // match变动
    const { setFieldsValue } = this.props.form;
    if (this.props.match.params.version !== nextProps.match.params.version) {
      const { dispatch } = this.props;
      setFieldsValue({ productType: '', product: '', build: '', decorationStandard: '', area: '' });
      dispatch({
        type: 'PriceManageItems/clear',
      });
      this.setState({
        expandForm: false,
        productType: '',
        product: '',
        build: '',
        decorationStandard: '',
        area: '',
      });
    }
  }

  // 根据查询条件搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form, match } = this.props;
    const query = form.getFieldsValue();
    dispatch({
      type: 'PriceManageItems/saveQuery',
      payload: { query, category: match.params.category },
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form } = this.props;
    // const query = form.getFieldsValue();
    form.resetFields();
    this.setState({
      productType: '',
      product: '',
      build: '',
      decorationStandard: '',
      area: '',
    });
  };

  // 切换搜索条件的展示方式
  toggleForm = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { searchItems, match } = this.props;
    const { build, productType, product, decorationStandard } = this.state;
    // 获取显示的下拉框
    const formItems = utils.getSelects(match.params.category);
    // 组团
    let products = [];
    let productTypes = [];
    let builds = [];
    let areas = [];
    let decorationStandards = [];
    // 业态
    products = utils.getSearchTypeItems(searchItems.org_product, 'name', 'id');
    // 产品构成
    productTypes = utils.getSearchTypeItems(
      searchItems.org_product,
      'proProductName',
      'proProductCode',
    );
    // 楼栋
    builds = utils.getSearchTypeItems(searchItems.org_build, 'name', 'id');
    // 面积段
    areas = utils.getSearchTypeItems(searchItems.org_house_package, 'name', 'id');
    // 投资版产品属性在楼栋 否在产品构成上
    if (match.params.category === 'investment') {
      decorationStandards = _.concat(
        decorationStandards,
        utils.getSearchTypeItems(searchItems.org_product, 'freeTypeName', 'freeTypeName'),
        utils.getSearchTypeItems(searchItems.org_product, 'businessTypeName', 'businessTypeName'),
        utils.getSearchTypeItems(searchItems.org_product, 'proTypeName', 'proTypeName'),
      );
    } else {
      decorationStandards = _.concat(
        decorationStandards,
        utils.getSearchTypeItems(searchItems.org_build, 'freeTypeName', 'freeTypeName'),
        utils.getSearchTypeItems(searchItems.org_build, 'businessTypeName', 'businessTypeName'),
        utils.getSearchTypeItems(searchItems.org_build, 'proTypeName', 'proTypeName'),
      );
    }

    if (productType) {
      let orgProduct = [];
      orgProduct = _.filter(searchItems.org_product, { proProductName: productType });
      products = utils.getSearchSeltetItems(orgProduct, 'org_product', 'name', 'id');
      builds = utils.getSearchSeltetItems(orgProduct, 'org_build', 'name', 'id');
      areas = utils.getSearchSeltetItems(orgProduct, 'org_house_package', 'name', 'id');
      // 投资版产品属性在楼栋 否在产品构成上
      if (match.params.category === 'investment') {
        decorationStandards = _.concat(
          utils.getSearchSeltetItems(orgProduct, 'org_product', 'freeTypeName', 'freeTypeName'),
          utils.getSearchSeltetItems(
            orgProduct,
            'org_product',
            'businessTypeName',
            'businessTypeName',
          ),
          utils.getSearchSeltetItems(orgProduct, 'org_product', 'proTypeName', 'proTypeName'),
        );
      } else {
        decorationStandards = _.concat(
          utils.getSearchSeltetItems(orgProduct, 'org_build', 'freeTypeName', 'freeTypeName'),
          utils.getSearchSeltetItems(
            orgProduct,
            'org_build',
            'businessTypeName',
            'businessTypeName',
          ),
          utils.getSearchSeltetItems(orgProduct, 'org_build', 'proTypeName', 'proTypeName'),
        );
      }
    }

    if (product) {
      let orgProduct = [];
      orgProduct = _.filter(searchItems.org_product, { name: product });
      builds = utils.getSearchSeltetItems(orgProduct, 'org_build', 'name', 'id');
      areas = utils.getSearchSeltetItems(orgProduct, 'org_house_package', 'name', 'id');
      // 投资版产品属性在楼栋 否在产品构成上
      if (match.params.category === 'investment') {
        decorationStandards = _.concat(
          utils.getSearchSeltetItems(orgProduct, 'org_product', 'freeTypeName', 'freeTypeName'),
          utils.getSearchSeltetItems(
            orgProduct,
            'org_product',
            'businessTypeName',
            'businessTypeName',
          ),
          utils.getSearchSeltetItems(orgProduct, 'org_product', 'proTypeName', 'proTypeName'),
        );
      } else {
        decorationStandards = _.concat(
          utils.getSearchSeltetItems(orgProduct, 'org_build', 'freeTypeName', 'freeTypeName'),
          utils.getSearchSeltetItems(
            orgProduct,
            'org_build',
            'businessTypeName',
            'businessTypeName',
          ),
          utils.getSearchSeltetItems(orgProduct, 'org_build', 'proTypeName', 'proTypeName'),
        );
      }
    }

    if (build) {
      let orgBuild = [];
      orgBuild = _.filter(searchItems.org_build, { name: build });
      areas = utils.getSearchSeltetItems(orgBuild, 'org_house_package', 'name', 'id');
      decorationStandards = _.concat(
        utils.getSearchSeltetItems(orgBuild, 'org_build', 'freeTypeName', 'freeTypeName'),
        utils.getSearchSeltetItems(orgBuild, 'org_build', 'businessTypeName', 'businessTypeName'),
        utils.getSearchSeltetItems(orgBuild, 'org_build', 'proTypeName', 'proTypeName'),
      );
    }

    if (decorationStandard) {
      let orgHousePackage = [];
      orgHousePackage = _.filter(
        searchItems.org_build,
        data =>
          data.freeTypeName === decorationStandard ||
          data.businessTypeName === decorationStandard ||
          data.proTypeName === decorationStandard,
      );
      areas = utils.getSearchSeltetItems(orgHousePackage, 'org_house_package', 'name', 'id');
    }

    const options = {
      products,
      areas,
      productTypes,
      builds,
      decorationStandards,
    };
    return (
      <Form onSubmit={this.handleSearch} layout="inline" className="form">
        <Row type="flex" justify="center" align="middle">
          <Col md={20} sm={24}>
            {formItems.map(selects => (
              <FormItem label={selects.label}>
                {getFieldDecorator(
                  selects.id,
                  {},
                )(
                  <Select
                    size="small"
                    dropdownMatchSelectWidth={false}
                    style={{ width: 120 }}
                    onChange={value => {
                      if (selects.id === 'productType') {
                        setFieldsValue({
                          product: '',
                          build: '',
                          area: '',
                          decorationStandard: '',
                        });
                        this.setState({
                          productType: value.split('|')[0],
                          product: '',
                          build: '',
                          area: '',
                          decorationStandard: '',
                        });
                      } else if (selects.id === 'product') {
                        setFieldsValue({
                          build: '',
                          area: '',
                          decorationStandard: '',
                        });
                        this.setState({
                          product: value.split('|')[0],
                          build: '',
                          area: '',
                          decorationStandard: '',
                        });
                      } else if (selects.id === 'build') {
                        setFieldsValue({
                          area: '',
                          decorationStandard: '',
                        });
                        this.setState({
                          build: value.split('|')[0],
                          area: '',
                          decorationStandard: '',
                        });
                      } else if (selects.id === 'decorationStandard') {
                        setFieldsValue({
                          area: '',
                        });
                        this.setState({
                          decorationStandard: value.split('|')[0],
                          area: '',
                        });
                      } else if (selects.id === 'area') {
                        this.setState({
                          area: value.split('|')[0],
                        });
                      }
                    }}
                    placeholder="请选择"
                  >
                    <Option value="">全部</Option>
                    {options[selects.datakey] && options[selects.datakey].length > 0
                      ? options[selects.datakey].map(value => (
                          <Option key={value.code} value={`${value.name}`}>
                            {value.name}
                          </Option>
                        ))
                      : ''}
                  </Select>,
                )}
              </FormItem>
            ))}
          </Col>
          <Col justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  // 点击获取待办id
  getStayToThingId = item => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
      item,
    });
  };

  /**
   * @Descripttion: 点击刷新
   * @param {*}
   * @return {*}
   */
  clickRefresh = () => {
    showConfirm(
      async () => {
        const response = await api.refreshPriceValueByStageIdUsingPOST({
          params: { projectFid: this.props.match.params.stage },
        });
        if (response?.code === 1) {
          message.success(response.message, 1, this.props.upData());
        }
      },
      '确定刷新最新实际销售数据吗？',
      '刷新最新实际销售数据，请耐心等待！',
    );
  };

  // 导出报表
  overAllValueExport = () => {
    const { match } = this.props;
    const params = {
      versionId: match.params.version,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/price/priceExcelExport?${exportQueryString}`);
  };

  /**
   * @Descripttion: 生成版本信息数据
   * @param {*} versionInfo 当前版本信息
   * @return {*} object
   */
  setBasicInfoData = versionInfo => {
    const basicInfo = [
      {
        span: 2,
        label: '版本名称',
        value: setValueReportVersionName(versionInfo),
      },
      {
        label: '创建人',
        value: versionInfo.createUser,
      },
      {
        label: '创建时间',
        value: moment(versionInfo.createTime).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        label: '创建方式',
        value: versionInfo.createMethod,
      },
    ];
    if (versionInfo.updateTime) {
      basicInfo.push({
        label: '更新时间',
        value: moment(versionInfo.updateTime).format('YYYY-MM-DD HH:mm:ss'),
      });
    }

    basicInfo.push({
      label: '操盘方式',
      value: versionInfo.isMarket === 'market' ? '营销操盘' : '营销不操盘',
    });
    const accessInfo = [
      {
        label: '面积版本',
        value: versionInfo?.versionAreaSource || '-',
      },
      {
        label: '楼栋计划',
        value: versionInfo?.versionBuildSource || '-',
      },
    ];

    return {
      basicInfo,
      accessInfo,
    };
  };

  /**
   * @Descripttion: 查看审批
   * @param {*}
   * @return {*}
   */
  clickViewApproval = async () => {
    const response = await apis.goodsApprovedViewUsingGET({
      params: {
        versionId: this.props.match.params.version,
      },
    });

    if (response?.code === 1 && response.data.status * 1 === 1) {
      window.open(`${response.data.url}`);
    }
  };

  render() {
    const { params } = this.props.match;
    const activeKey = params.category;
    const { versions, agentInfo, versionDetail } = this.props;
    const { visible, item, expandForm } = this.state;
    return (
      <>
        {visible ? (
          <Alteration
            visible={visible}
            handleCancel={() => this.setState({ visible: !visible })}
            match={this.props.match}
            item={item}
          />
        ) : null}
        {!params.edit ? (
          <div className="header-categories">
            <Tabs
              activeKey={activeKey}
              animated={false}
              onChange={key => {
                router.push(
                  `/ValueManage/PriceManage/${params.level1}/${params.level2}/${params.project}/${params.stage}/${key}`,
                );
              }}
              size="large"
              tabBarExtraContent={
                <Row type="flex">
                  <Col>
                    {!_.isEmpty(agentInfo) && (
                      <TextScroll
                        agentInfo={agentInfo}
                        getStayToThingId={v => this.getStayToThingId(v)}
                      />
                    )}
                  </Col>
                  <Col>
                    {/* 战规版 and 投资版 显示创建异常版本按钮 */}
                    {['strategy', 'investment'].includes(activeKey) && (
                      <AuthorizedButton authority="HZTB_CREATE_EXCEPTION_VERSION">
                        <Button
                          type="primary"
                          className="red-button"
                          onClick={this.props?.clickCreateExceptionVersion}
                        >
                          创建异常版本
                        </Button>
                        &nbsp;&nbsp;
                      </AuthorizedButton>
                    )}
                    {['dynamic'].includes(activeKey) && (
                      <AuthorizedButton authority="HZTB_CREATE_UNIVERSAL_VERSION">
                        <Button type="primary" onClick={this.props?.clickCreatePopularTuneVersion}>
                          创建普调版本
                        </Button>
                        &nbsp;&nbsp;
                      </AuthorizedButton>
                    )}
                    <AuthorizedButton authority="HZTB_CREATE_VERSION">
                      <Button type="primary" onClick={this.props?.clickCreateVersion}>
                        创建版本
                      </Button>
                      &nbsp;&nbsp;
                    </AuthorizedButton>
                  </Col>
                </Row>
              }
            >
              <TabPane tab="月度动态版" key="dynamic" />
              <TabPane tab="大定价版" key="pricing" />
              <TabPane tab="战规版" key="strategy" />
              <TabPane tab="投资版" key="investment" />
            </Tabs>
            {/* 内容-搜索-创建-编辑。。。。 */}
            {/*
             待提交审批-审批中-审批已驳回-审批通过
             NOTPREPARED("not_prepared","待编制"),
             ORGANIZATION("organization","编制中"),
             EXAMINEDAPPROVED("examined_approved","待提交审批"),
             APPROVED("approved","审批中"),
             FAILUREAPPROVED("failure_approved","审批已驳回"),
             SUCCESSAPPROVED("success_approved","审批通过"),
             SYSGENERATION("sys_generation","系统生成"), */}
            {!_.isEmpty(versionDetail) ? (
              <Row type="flex" justify="space-between" align="middle">
                {/* 版本信息 */}
                <Col>
                  <Row type="flex" align="middle" gutter={[20, 0]}>
                    <Col>
                      <Select
                        style={{ minWidth: '175px' }}
                        size="small"
                        onChange={value => {
                          router.replace(
                            `/ValueManage/PriceManage/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                          );
                        }}
                        dropdownMatchSelectWidth={false}
                        value={versionDetail.versionId}
                      >
                        {versions.map(val => (
                          <Option key={val.versionId} value={val.versionId}>
                            {setValueReportVersionName(val)}
                          </Option>
                        ))}
                      </Select>
                    </Col>
                    <Col>
                      {params.edit ? (
                        <Text className="version-current">
                          {setValueReportVersionName(versionDetail)}
                        </Text>
                      ) : null}
                      <ApprovalStatus applyType={versionDetail?.versionStateCode} />
                      &nbsp;&nbsp;
                      <MyBasicInfo data={this.setBasicInfoData(versionDetail)} />
                    </Col>
                  </Row>
                </Col>
                <Col>
                  {/* 刷新 */}
                  <>
                    {/* *1.月度动态版显示
                     *2.如果月度动态版下存在版本判断最新版本是系统生产 或 审批通过
                     *3.只在最新版本状态 显示 */}
                    {['dynamic'].includes(activeKey) &&
                      versions[0]?.versionId === versionDetail?.versionId &&
                      ['success_approved', 'sys_generation'].includes(
                        versionDetail?.versionStateCode,
                      ) && (
                        <AuthorizedButton authority="HZTB_REFRESH">
                          <Button icon="reload" onClick={this.clickRefresh}>
                            刷新
                          </Button>
                          &nbsp;&nbsp;
                        </AuthorizedButton>
                      )}
                  </>
                  {/* 设为考核版 */}
                  <>
                    {/* 是投资版 并且当前版本不是考核版 */}
                    {['investment'].includes(activeKey) &&
                      Number(versionDetail?.isAssessmentVersion) === 0 && (
                        <AuthorizedButton authority="HZTB_SET_ASSESSMENT_VERSION">
                          <Button
                            type="primary"
                            className="red-button"
                            onClick={this.props?.clickCreateVersion}
                          >
                            设为考核版
                          </Button>
                          &nbsp;&nbsp;
                        </AuthorizedButton>
                      )}
                  </>
                  {/* 查看审批 */}
                  <>
                    {/* 待提交审批，审批中 审批已驳回  审批通过 */}
                    {[
                      'examined_approved',
                      'approved',
                      'failure_approved',
                      'success_approved',
                    ].includes(versionDetail?.versionStateCode) && (
                      <AuthorizedButton authority="HZTB_VIEW_APPROVAL">
                        <Button className="yellow-button" onClick={this.clickViewApproval}>
                          查看审批
                        </Button>
                        &nbsp;&nbsp;
                      </AuthorizedButton>
                    )}
                  </>
                  {/* 编辑价格 */}
                  <>
                    {/* 待编制,编制中,待提交审批,审批已驳回 显示编辑 */}
                    {[
                      'not_prepared',
                      'organization',
                      'examined_approved',
                      'failure_approved',
                    ].includes(versionDetail?.versionStateCode) && (
                      <>
                        {versionDetail?.batchAdjust * 1 === 0 && (
                          <AuthorizedButton authority="HZTB_EDIT_PRICE">
                            <Button
                              type="primary"
                              onClick={() => {
                                router.push(`${this.props.match.url}/edit`);
                              }}
                            >
                              编辑价格
                            </Button>
                            &nbsp;&nbsp;
                          </AuthorizedButton>
                        )}

                        {versionDetail?.batchAdjust * 1 === 1 && (
                          <AuthorizedButton authority="HZTB_EDIT_UNIVERSAL_PRICE">
                            <Button
                              type="primary"
                              onClick={() => {
                                router.push(`${this.props.match.url}/edit`);
                              }}
                            >
                              编辑普调价格
                            </Button>
                            &nbsp;&nbsp;
                          </AuthorizedButton>
                        )}
                      </>
                    )}
                  </>
                  {/* 删除版本 */}
                  <>
                    {/* 待编制,编制中 显示删除版本 */}
                    {['not_prepared', 'organization'].includes(versionDetail?.versionStateCode) && (
                      <>
                        {versionDetail?.batchAdjust * 1 === 0 && (
                          <AuthorizedButton authority="HZTB_DELETE_VERSION">
                            <Button type="primary" onClick={this.props?.clickDeleteVersion}>
                              删除版本
                            </Button>
                            &nbsp;&nbsp;
                          </AuthorizedButton>
                        )}

                        {versionDetail?.batchAdjust * 1 === 1 && (
                          <AuthorizedButton authority="HZTB_DELETE_UNIVERSAL_VERSION">
                            <Button type="primary" onClick={this.props?.clickDeleteVersion}>
                              删除普调版本
                            </Button>
                            &nbsp;&nbsp;
                          </AuthorizedButton>
                        )}
                      </>
                    )}
                  </>
                  <AuthorizedButton authority="HZTB_EXPORT_VERSION">
                    <Button className="yellow-button" onClick={this.overAllValueExport}>
                      导出报表
                    </Button>
                    &nbsp;&nbsp;
                  </AuthorizedButton>
                  <Button onClick={this.toggleForm}>
                    高级筛选
                    <Icon type={expandForm ? 'up' : 'down'} />
                  </Button>
                </Col>
              </Row>
            ) : null}
            <>{expandForm && this.renderAdvancedForm()}</>
          </div>
        ) : (
          <Row className="version-bg-color" type="flex" justify="space-between" align="middle">
            <Col>
              {!_.isEmpty(versionDetail) ? (
                <>
                  <Text>{setValueReportVersionName(versionDetail)}</Text>
                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  <ApprovalStatus applyType={versionDetail?.versionStateCode} />
                  &nbsp;&nbsp;
                  {versionDetail?.versionAreaSource ? (
                    <Text>{`基于面积计划版本：${versionDetail?.versionAreaSource}`}，</Text>
                  ) : null}
                  {versionDetail?.versionBuildSource ? (
                    <Text>{`基于楼栋计划版本：${versionDetail?.versionBuildSource}`}</Text>
                  ) : null}
                  &nbsp;&nbsp;
                  <Text>
                    &nbsp;&nbsp; {versionDetail?.isMarket === 'market' ? '营销操盘' : '营销不操盘'}
                  </Text>
                </>
              ) : null}
            </Col>
            {versionDetail?.batchAdjust * 1 === 1 ? (
              <Col>
                <span className="color-red">调整后均价不可超过调整前均价的正负 20%</span>
                &nbsp;&nbsp;
                <Button size="small" type="primary" onClick={this.props?.clickBatchOperation}>
                  批量调整
                </Button>
              </Col>
            ) : null}
          </Row>
        )}
      </>
    );
  }
}
